<template>
  <cloud-dialog
    v-model:visible="visible"
    :width="448"
    title="修改账号"
    :loading="loading"
    :before-ok="handleOk"
    :mask-closable="false"
    :before-open="handleOpen">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item
        field="username"
        label="账号"
        validate-trigger="blur"
        hide-asterisk
        asterisk-position="end">
        <a-input v-model="formData.username" placeholder="请输入账号" />
      </a-form-item>
    </a-form>
  </cloud-dialog>
</template>
<script lang="ts" setup>
import { updateApiUserApi } from '@/apis/modules/auth'
import { useAppStore } from '@/stores/app'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'

const visible = defineModel<boolean>({ required: true })
const loading = ref(false)
const formRef = ref<FormInstance>()

const formData = reactive<any>({
  username: ''
})
const appStore = useAppStore()

const rules: Record<string, FieldRule> = {
  username: {
    required: true,
    validator(value, callback: (error?: string) => void) {
      const reg = /^[a-zA-Z0-9_]{4,18}$/
      if (!value) {
        return callback('请输入账号')
      }
      if (!reg.test(value)) {
        return callback('请输入4-18个字符，可包含英文字母、数字、下划线')
      }
      callback()
    }
  }
}
const handleOk = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  loading.value = true
  return updateApiUserApi(formData).then(() => {
    formRef.value?.resetFields()
    ToastUtils.success('修改成功')
    appStore.clearLoginInfoAction()
  })
}
const handleOpen = async () => {
  formData.username = appStore.userInfo?.username
}
</script>
